﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.ETL.Domain.Services
{
    public class DataVerificationRuleService
    {
        public ServiceResult Create(string userId, Guid dtTableId, string caption, string condition, int type, string parameterSettings)
        {
            if(string.IsNullOrEmpty(parameterSettings) && type == DEF.DataVerificationRuleType.StoredProcedure)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            string[] parameterKVArr = null;
            if (type == DEF.DataVerificationRuleType.StoredProcedure)
            {
                parameterKVArr = parameterSettings.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (parameterKVArr.Length % 2 != 0)
                {
                    return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
                }
            }
            using(EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDataVerificationRule> dvrRep = new EntityRepository<Entities.EDataVerificationRule>(dbContext);
                EntityRepository<Entities.EDVRParameter> dvrpRep = new EntityRepository<Entities.EDVRParameter>(dbContext);

                Entities.EDataVerificationRule eDVR = new Entities.EDataVerificationRule();
                eDVR.Id = Guid.NewGuid();
                eDVR.Caption = caption;
                eDVR.Type = type;
                eDVR.Condition = condition;
                eDVR.DtTableId = dtTableId;
                eDVR.CreatedTime = DateTime.Now;
                eDVR.Creator = userId;

                dvrRep.Create(eDVR);

                if (parameterKVArr != null)
                {
                    for (int index = 0; index < parameterKVArr.Length; index += 2)
                    {
                        Entities.EDVRParameter param = new Entities.EDVRParameter();
                        param.Id = Guid.NewGuid();
                        param.DVRId = eDVR.Id;
                        param.Name = parameterKVArr[index];
                        param.Value = parameterKVArr[index + 1];
                        param.Index = index / 2;
                        dvrpRep.Create(param);
                    }
                }

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult(true, ErrorCode.COM_NoError, string.Empty);
                }
                catch(Exception ex)
                {
                    return new ServiceResult(false, ErrorCode.COM_DBError, string.Empty);
                }
            }
        }

        public ListResult<Entities.EDataVerificationRule> GetList(Guid dtTableId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDataVerificationRule> dvrRep = new EntityRepository<Entities.EDataVerificationRule>(dbContext);
                List<Entities.EDataVerificationRule> list = dvrRep.GetList(p => p.DtTableId == dtTableId);

                return new ListResult<Entities.EDataVerificationRule>(true, ErrorCode.COM_NoError, string.Empty, list);
            }
        }

        public ServiceResult Delete(Guid id)
        {

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDataVerificationRule> dvrRep = new EntityRepository<Entities.EDataVerificationRule>(dbContext);

                Entities.EDataVerificationRule eDVR = dvrRep.Get(p => p.Id == id);

                if(eDVR!= null)
                {
                    dvrRep.Delete(eDVR);

                    try
                    {
                        if (dbContext.SaveChanges() > 0)
                        {
                            return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                        }
                        else
                        {
                            return new ServiceResult(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("删除数据审核规则失败:{0},ex:{1}", id, ex));
                        return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                    }
                }
                else
                {
                    Logger.WarningToTag(Library.LogTAG, string.Format("删除数据审核规则:{0},规则不存在", id));
                    return new ServiceResult(true, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
            }
        }
        public ServiceResult Update(string userId, Guid id, string condition, int type, string parameterSettings)
        {
            if (string.IsNullOrEmpty(parameterSettings) && type == DEF.DataVerificationRuleType.StoredProcedure)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            string[] parameterKVArr = null;
            if (type == DEF.DataVerificationRuleType.StoredProcedure)
            {
                parameterKVArr = parameterSettings.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (parameterKVArr.Length % 2 != 0)
                {
                    return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
                }
            }

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDataVerificationRule> dvrRep = new EntityRepository<Entities.EDataVerificationRule>(dbContext);
                EntityRepository<Entities.EDVRParameter> dvrpRep = new EntityRepository<Entities.EDVRParameter>(dbContext);

                Entities.EDataVerificationRule eDVR = dvrRep.Get(p => p.Id == id);
                if (eDVR != null)
                {
                    eDVR.Type = type;
                    eDVR.Condition = condition;
                    eDVR.CreatedTime = DateTime.Now;
                    eDVR.Creator = userId;

                    dvrRep.Update(eDVR);

                    // 删除已有参数重新创建
                    dbContext.Database.ExecuteSqlCommand("delete from ETL_DVRParameter where dvrid={0}", eDVR.Id);

                    if (parameterKVArr != null)
                    {
                        for (int index = 0; index < parameterKVArr.Length; index += 2)
                        {
                            Entities.EDVRParameter param = new Entities.EDVRParameter();
                            param.Id = Guid.NewGuid();
                            param.DVRId = eDVR.Id;
                            param.Name = parameterKVArr[index];
                            param.Value = parameterKVArr[index + 1];
                            param.Index = index / 2;
                            dvrpRep.Create(param);
                        }
                    }

                    try
                    {
                        dbContext.SaveChanges();
                        return new ServiceResult(true, ErrorCode.COM_NoError, string.Empty);
                    }
                    catch(Exception ex)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("更新数据审核规则失败:{0},ex:{1}", id, ex));
                        return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                    }
                }
                else
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("更新数据审核规则失败:{0},规则不存在", id));
                    return new ServiceResult(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
            }
        }

        public ServiceResult<Data.DataVerificationRule> Get(Guid id)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDataVerificationRule> dvrRep = new EntityRepository<Entities.EDataVerificationRule>(dbContext);
                EntityRepository<Entities.EDVRParameter> dvrpRep = new EntityRepository<Entities.EDVRParameter>(dbContext);

                Entities.EDataVerificationRule item = dvrRep.Get(p => p.Id == id);
                Data.DataVerificationRule rule = new Data.DataVerificationRule();
                rule.Rule = item;
                rule.Parameters = dvrpRep.GetList(p => p.DVRId == item.Id);
                return new ServiceResult<Data.DataVerificationRule>(true, ErrorCode.COM_NoError, string.Empty, rule);
            }
        }
    }
}
